<template>
  <div class="create-batch-container">
    <div class="page-header">
      <el-button @click="goBack" text>
        <el-icon><ArrowLeft /></el-icon>
        返回列表
      </el-button>
      <h1>{{ isEditMode ? '编辑茶叶批次' : '创建茶叶批次' }}</h1>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="create-form"
      v-loading="loading"
    >
      <el-card class="form-card">
        <template #header>
          <h3>基本信息</h3>
        </template>
        
        <el-row :gutter="20">
          <el-col :md="12">
            <el-form-item label="茶叶名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入茶叶名称" />
            </el-form-item>
          </el-col>
          <el-col :md="12">
            <el-form-item label="茶叶品种" prop="variety">
              <el-input v-model="form.variety" placeholder="请输入茶叶品种" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :md="12">
            <el-form-item label="茶叶等级" prop="grade">
              <el-select v-model="form.grade" placeholder="请选择等级">
                <el-option label="特级" value="特级" />
                <el-option label="一级" value="一级" />
                <el-option label="二级" value="二级" />
                <el-option label="三级" value="三级" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="产品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入产品描述"
          />
        </el-form-item>
      </el-card>

      <el-card class="form-card">
        <template #header>
          <h3>产地信息</h3>
        </template>

        <el-row :gutter="20">
          <el-col :md="8">
            <el-form-item label="省份" prop="production.origin.province">
              <el-input v-model="form.production.origin.province" placeholder="省份" />
            </el-form-item>
          </el-col>
          <el-col :md="8">
            <el-form-item label="城市" prop="production.origin.city">
              <el-input v-model="form.production.origin.city" placeholder="城市" />
            </el-form-item>
          </el-col>
          <el-col :md="8">
            <el-form-item label="县区" prop="production.origin.county">
              <el-input v-model="form.production.origin.county" placeholder="县区（可选）" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="采摘日期" prop="production.harvestDate">
          <el-date-picker
            v-model="form.production.harvestDate"
            type="date"
            placeholder="选择采摘日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-card>

      <div class="form-actions">
        <el-button @click="goBack">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEditMode ? '更新批次' : '创建批次' }}
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { apiMethods } from '@/api'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 状态
const formRef = ref(null)
const submitting = ref(false)
const loading = ref(false)

// 编辑模式检测
const isEditMode = computed(() => !!route.params.id)
const batchId = computed(() => route.params.id)

// 表单数据
const form = reactive({
  name: '',
  variety: '',
  grade: '',
  description: '',
  production: {
    origin: {
      province: '',
      city: '',
      county: ''
    },
    harvestDate: ''
  }
})

// 验证规则
const rules = {
  name: [
    { required: true, message: '请输入茶叶名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在1-100个字符', trigger: 'blur' }
  ],
  variety: [
    { required: true, message: '请输入茶叶品种', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在1-50个字符', trigger: 'blur' }
  ],
  'production.origin.province': [
    { required: true, message: '请输入省份', trigger: 'blur' }
  ],
  'production.origin.city': [
    { required: true, message: '请输入城市', trigger: 'blur' }
  ],
  'production.harvestDate': [
    { required: true, message: '请选择采摘日期', trigger: 'change' }
  ]
}

// 方法
const goBack = () => {
  router.back()
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    submitting.value = true

    let response
    if (isEditMode.value) {
      response = await apiMethods.batches.update(batchId.value, form)
    } else {
      response = await apiMethods.batches.create(form)
    }
    
    if (response.data.success) {
      ElMessage.success(isEditMode.value ? '批次更新成功' : '批次创建成功')
      router.push('/batches')
    } else {
      ElMessage.error(response.data.message)
    }
  } catch (error) {
    if (error !== false) { // 排除表单验证失败
      console.error(isEditMode.value ? '更新批次失败:' : '创建批次失败:', error)
      ElMessage.error(isEditMode.value ? '更新批次失败，请重试' : '创建批次失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

// 加载批次数据（编辑模式）
const loadBatchData = async () => {
  if (!isEditMode.value) return
  
  loading.value = true
  
  try {
    const response = await apiMethods.batches.getById(batchId.value)
    
    if (response.data.success) {
      const batch = response.data.data.batch
      
      // 填充表单数据
      form.name = batch.name || ''
      form.variety = batch.variety || ''
      form.grade = batch.grade || ''
      form.description = batch.description || ''
      
      if (batch.production) {
        form.production.origin.province = batch.production.origin?.province || ''
        form.production.origin.city = batch.production.origin?.city || ''
        form.production.origin.county = batch.production.origin?.county || ''
        
        if (batch.production.harvestDate) {
          form.production.harvestDate = new Date(batch.production.harvestDate).toISOString().split('T')[0]
        }
      }
    } else {
      ElMessage.error('加载批次数据失败')
      router.back()
    }
  } catch (error) {
    console.error('加载批次数据失败:', error)
    ElMessage.error('加载批次数据失败')
    router.back()
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  loadBatchData()
})
</script>

<style scoped>
.create-batch-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 12px;
}

.page-header h1 {
  margin: 0;
  color: #2c3e50;
}

.form-card {
  margin-bottom: 20px;
}

.form-card :deep(.el-card__header) {
  padding: 18px 20px;
  border-bottom: 1px solid #ebeef5;
}

.form-card h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 16px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 20px 0;
}

/* 响应式 */
@media (max-width: 768px) {
  .create-batch-container {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .create-form :deep(.el-form-item__label) {
    width: 100px !important;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .form-actions .el-button {
    width: 100%;
  }
}
</style>